'use strict';

const BaseController = require('./base');

class ArticlesController extends BaseController {
  // 查询
  async index() {
    /* 
    const { ctx } = this; // categories?page=1&pageSize=5&keyword=a
    let {pageNum=1, pageSize=5, keyword} = ctx.query;
    pageNum = isNaN(pageNum)? 1: parseInt(pageNum);
    pageSize = isNaN(pageSize)? 5: parseInt(pageSize);
    let query = {};
    if (keyword) {
      // 关键字在 title 和content里面进行匹配
      query['$or'] = [{title: new RegExp(keyword)},
                      {content: new RegExp(keyword)}]
    }
    */

    try {
      // skip跳过执行条数
      // let items = await ctx.model.Article.find(query)
      //     .skip((pageNum - 1) * pageSize)
      //     .limit(pageSize);
      // 使用封装的方法进行请求
      
      await this.getPager({
                  modelName: 'Article', 
                  fields: ['title', 'content'], 
                  populateFields: ['category']
                });
      // this.success(items)
    } catch (error) {
      this.error(error);
    }
  }
  // 增加文章分类
  async create() {
    const { ctx } = this;
    let article = ctx.request.body;
    // 设置当前发表文章的作者
    article.user = this.user; //   
    try {
      article = await ctx.model.Article.create(article);
      this.success('文章发表成功')
    } catch (error) {
      this.error(error);
    }
    
  }

  async update() {
    const { ctx } = this;
    // api/categories/:id
    // 通过以下方式来取参数
    let id = ctx.params.id;
    let article = ctx.request.body;

    try {
      let result = await ctx.model.Article.findByIdAndUpdate(id, article);
      this.success('更新成功');
    } catch (error) {
      this.error(error);
    }
  }

  async destroy() {
    const { ctx } = this;
    let id = ctx.params.id;
    let {ids = []} = ctx.request.body;
    ids.push(id);
    try {
      await ctx.model.Article.remove({_id: {$in: ids}});
      // await ctx.model.Article.findByIdAndRemove(id);
      this.success('删除成功');
    } catch (error) {
      this.error(error);
    }
  }
  // 阅读
  async addPv(){
    const {ctx} = this;
    let id = ctx.params.id;
    try {
      // {$inc: {pv: 1}}  pv 加1
      await ctx.model.Article.findByIdAndUpdate(id, {$inc: {pv: 1}});
    } catch (error) {
      this.error(error);
    }
  }

  // 评论
  async addComment(){
    const {ctx} = this;
    let id = ctx.params.id;
    let comment = ctx.request.body;
    comment.user = this.user._id;
    try {
      let result = await ctx.model.Article.findByIdAndUpdate(id, {$push: {comments: comment}});
      this.success('评论成功');
    } catch (error) {
      this.error(error);
    }
  }

}

module.exports = ArticlesController;